<template>
  <div>
    <div class="city__searchWrap">
      <input v-model="keyword" class="city__search" type = "text" placeholder="输入城市名称或者拼音">
    </div>
    <div class="city__search-content" ref="wrap" v-show="keyword">
      <ul>
        <li class="item border-bottom"
            v-for = "item of list"
            :key = "item.id"
            @click="handleCityClick(item.name)"
        >{{item.name}}</li>
        <li class="item border-bottom"  v-show = "hasNoData">没有找到相关的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'citySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeIt', city)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrap)
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = {}
        return
      }
      this.timer = setTimeout(() => {
        const res = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              res.push(value)
            }
          })
        }
        this.list = res
      }, 100)
    }
  }
}
</script>

<style lang='stylus' scoped>
.city__searchWrap
  padding: 10px
  background: #00bcd4
  .city__search
    height: 60px
    width: 100%
    line-height 60px
    font-size: 24px;/*px*/
    color: #666
    text-align: center
    border-radius: 6px
.city__search-content
  overflow: hidden
  position: absolute
  top: 166px
  left: 0
  right: 0
  bottom: 0
  z-index: 999
  background: #eee
  .item
    padding-left: 20px;
    height: 70px;
    line-height: 70px;
    color: #666;
    background: #fff
    &.border-bottom:before
      border-color: #ccc;
</style>
